package interview_service

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"net/http"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/utils/tools"
)

type INextQuestion interface {
	NextQuestion(int) []byte
	CacheNextQues(Client) error
	getTotal() int
	FirstQuesVideo() []byte
	getFinishedStatus() int
}

type IRecommend interface {
	getTotal() int
	getQuesTypeOrder() map[int]string
}

type NextQuesReq struct {
	Query []struct {
		QuestionID uint   `json:"c_question_id"`
		Question   string `json:"question"`
		Answer     string `json:"answer"`
	} `json:"querys"`
	Name string `json:"name"`
}

type QuesInfo struct {
	Type string   `json:"type"`
	Key  []string `json:"key"`
}

type ConvSessionRes struct {
	Status string `json:"status"`
	Code   int16  `json:"code"`
	Data   struct {
		Grade float64 `json:"grade"`
	} `json:"data"`
}

func JudgeScore(score float64) string {
	if score <= 0.5 && score >= 0 {
		return "差"
	} else if score > 0.5 && score < 0.75 {
		return "中"
	} else {
		return "好"
	}
}

func ConvSession(r *tables.RealQues, answer string) (*tables.MarginVideo, error) {
	reqData, _ := json.Marshal(map[string]string{"query": answer})
	log.ZapLogger.Info("请求转场服务: " + string(reqData))
	resp, err := http.Post(variable.Config.Services.ConvSession, "application/json", bytes.NewReader(reqData))
	if err != nil {
		return nil, fmt.Errorf("转场评分请求失败, %s", err.Error())
	}
	res := new(ConvSessionRes)
	err = tools.ReadResponseBody(resp, res)
	if err != nil {
		return nil, fmt.Errorf("转场评分相应结果解析失败, %s", err.Error())
	}
	r.Score = res.Data.Grade
	// 转场评分已经废弃, 可以删除该字段
	variable.DB.MySQL.Model(&r).Where("id = ?", r.ID).Updates(map[string]interface{}{"score": r.Score})
	// variable.DB.MySQL.Update(r)
	criteria := JudgeScore(r.Score)
	marginVideos := make([]*tables.MarginVideo, 10)
	if err = variable.DB.MySQL.
		Where("tag=? and type=?", criteria, "convert").
		Find(&marginVideos).Error; err != nil {
		return nil, err
	}
	if len(marginVideos) <= 0 {
		return nil, errors.New("无可用转场视频")
	}
	randSub := rand.Intn(len(marginVideos))
	return marginVideos[randSub], nil
}
